﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using BinLibrary.WinHelper;
using RevitReadAutoCAD;
using Teigha.Core;
using Teigha.TD;
using RevitReadAutoCAD.TeighaHelper;

#region Copyright
/************************************************************************************ 
 * Copyright (c) 2017Microsoft All Rights Reserved. 
 * CLR版本： 4.0.30319.18444 
 *机器名称：MDELL-PC-XZB 
 *公司名称：Microsoft 
 *命名空间：$rootnamespace$ 
 *文件名：  Class1 
 *版本号：  V1.0.0.0 
 *唯一标识：cab6412c-0eb8-4290-ba35-6f4ebad7bbc4 
 *当前的用户域：MDELL-PC-XZB 
 *创建人：  xuzhaobin 
 *电子邮箱：384785044@qq.com 
 *创建时间：2017/1/13 14:34:10 
 *描述： 
 * 
 *===================================================================== 
 *修改标记 
 *修改时间：2017/1/13 14:34:10 
 *修改人： 徐召彬 
 *版本号： V1.0.0.0 
 *描述： 
 * 
/************************************************************************************/
#endregion
namespace externalCMD
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    public class HelloWorldReadCAD : IExternalCommand
    {
        static HelloWorldReadCAD()
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
        }

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "DWG Files (*.dwg)|*.dwg";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string fileName = openFileDialog.FileName;
                    AppDomain currentdomain = AppDomain.CurrentDomain;

                    var assemblies = currentdomain.GetAssemblies();
                    var dwginfo = Utils.GetCADTextInfl1(fileName);


                    return Autodesk.Revit.UI.Result.Succeeded;
                }
                catch (Exception ex)
                {
                    string sss = ex.Message;
                    MessageBox.Show(sss);
                    return Autodesk.Revit.UI.Result.Failed;
                }
            }

            return Result.Succeeded;
        }

        private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var path2 = @"D:\Program Files\Hongye\HYMEI2018\bin";
            var searches = new List<string>();
            searches.Add(path2);
            //MessageBox.Show("resolving");

            var assemblyName = new AssemblyName(args.Name);

            foreach (var item in searches)
            {
                var file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));
                //MessageBox.Show(file);
                LogHelper.LogWrite(@"c:\lackofdlls.txt", "dll  is :" + file);
                if (File.Exists(file))
                {
                    return Assembly.LoadFile(file);
                }
            }

            return args.RequestingAssembly;
        }

        private Assembly OnassemblyResolve(object sender, ResolveEventArgs args)
        {
            lock (this)
            {
                var m_CurrentFile = Assembly.GetExecutingAssembly().Location;
                var path1 = @"C:\Users\XU\source\repos\RevitReadAutoCAD\RevitReadAutoCAD\dlls\HYTD";
                var EnvironmentPaths = new List<string>();
                EnvironmentPaths.Add(m_CurrentFile);
                EnvironmentPaths.Add(path1);

                var assemblyName = new AssemblyName(args.Name);

                var path = Path.GetDirectoryName(m_CurrentFile);

                var file = string.Format("{0}.dll", System.IO.Path.Combine(path, assemblyName.Name));

                if (File.Exists(file))
                {
                    return ResolveAssembly(file);
                }

                foreach (var item in EnvironmentPaths)
                {
                    file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));

                    if (File.Exists(file))
                    {
                        return ResolveAssembly(file);
                    }
                }

                return null;
            }
        }
        private Assembly ResolveAssembly(string file)
        {
            try
            {
                Monitor.Enter(this);
                return Assembly.LoadFile(file);
            }
            finally
            {
                Monitor.Exit(this);
            }
        }

       

        //public List<CADTextModel> GetCADTextInfo(string dwgFile)
        //{
        //    List<CADTextModel> listCADModels = new List<CADTextModel>();

        //    using (new Services())
        //    {
        //        using (Database database = new Database(true, true))
        //        {
        //            database.ReadDwgFile(dwgFile, FileShare.Read, false, "");
        //            using (var trans = database.TransactionManager.StartTransaction())
        //            {
        //                using (BlockTable table = (BlockTable)database.BlockTableId.GetObject(OpenMode.ForRead, false, true))
        //                {
        //                    using (SymbolTableEnumerator enumerator = table.GetEnumerator())
        //                    {
        //                        StringBuilder sb = new StringBuilder();
        //                        while (enumerator.MoveNext())
        //                        {
        //                            using (BlockTableRecord record = (BlockTableRecord)enumerator.Current.GetObject(OpenMode.ForRead))
        //                            {

        //                                foreach (ObjectId id in record)
        //                                {
        //                                    DBObject entity = id.GetObject(OpenMode.ForRead, false, false);
        //                                    CADTextModel model = new CADTextModel();
        //                                    switch (entity.GetRXClass().Name)
        //                                    {
        //                                        case "AcDbText":
        //                                            Teigha.DatabaseServices.DBText text = (Teigha.DatabaseServices.DBText)entity;
        //                                            if (text.Layer.Contains("标注") && !string.IsNullOrEmpty(text.TextString))
        //                                            {
        //                                                model.Location = ConverCADPointToRevitPoint(text.Position);
        //                                                model.Text = text.TextString;
        //                                                model.Angel = text.Rotation;
        //                                                model.Layer = text.Layer;
        //                                                listCADModels.Add(model);
        //                                            }
        //                                            break;
        //                                        case "AcDbMText":
        //                                            Teigha.DatabaseServices.MText mText = entity as Teigha.DatabaseServices.MText;
        //                                            if (mText != null && mText.Layer.Contains("标注"))
        //                                            {
        //                                                model.Location = ConverCADPointToRevitPoint(mText.Location);
        //                                                model.Text = mText.Text;
        //                                                model.Angel = mText.Rotation;
        //                                                model.Layer = mText.Layer;
        //                                                listCADModels.Add(model);
        //                                            }
        //                                            break;
        //                                    }
        //                                }
        //                            }
        //                        }

        //                    }
        //                }
        //            }

        //        }
        //    }



        //    return listCADModels;
        //}



        /// <summary>
        /// 毫米转化成英寸
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private double MillimetersToUnits(double value)
        {
            return UnitUtils.ConvertToInternalUnits(value, DisplayUnitType.DUT_MILLIMETERS);
        }

        /// <summary>
        /// 将CAD里的点转化为Revit里的点
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>


        public class CADTextModel
        {
            public string Text;
            public double Angel;
            public string Layer;
            public XYZ Location;
        }



    }

}
